import { createRef } from "react";
import RightNavItem from "../Item";
import { useState } from "react";
interface RightNavListItemProps {
  popover?: React.ReactNode;
}

const RightNavListItem: React.FC<React.PropsWithChildren<RightNavListItemProps>> = ({ children, popover }) => {
  const [open, setOpen] = useState(false);

  const WrapperRef = createRef<HTMLDivElement>();

  const handleClick = () => {

    const close = () => {
      window.removeEventListener("click", close);
      setOpen(false);
    }

    if (!open) {
      requestAnimationFrame(() => {
        window.addEventListener("click", close);
      })
      setOpen(true)
    }
  }

  return (
    <RightNavItem ref={WrapperRef} onClick={handleClick} className="pr-[18px]">
      {children}
      <i className="border-[5px] border-transparent border-t-white translate-x-[6px] translate-y-[4px]"></i>
      <div className={
        `z-[1000] absolute top-full left-1/2 inset-0 h-fit py-2 bg-black/90 rounded-[5px] shadow-[0_2px_4px_rgba(0,0,0,0.5)] -translate-x-1/2 translate-y-1 min-w-[117px] transition
        ${open ? 'opacity-100 pointer-events-auto scale-100' : 'opacity-0 pointer-events-none scale-90'}
      `}>
        {popover}
      </div>
    </RightNavItem>
  );
}

export default RightNavListItem